<?php
/* WordPress script loading 后台不用 */
if ( !is_admin() ) { 
      wp_deregister_script( 'jquery' ); // 取消原有的 jquery 定义
      wp_deregister_script( 'l10n' );
}
/* Remove Admin_bar  */
add_filter( 'show_admin_bar', '__return_false' ); 
/* Add HomePage to wiget menu */
function home_page_menu_args( $args ) {
    $args['show_home'] = true;
    return $args;
}
add_filter( 'wp_page_menu_args', 'home_page_menu_args' );
//------------end-----------
/*WordPress后台去除不必要的面板 */
function example_remove_dashboard_widgets() {
    // Globalize the metaboxes array, this holds all the widgets for wp-admin
    global $wp_meta_boxes;
    // 以下这一行代码将删除 "快速发布" 面板，如果你想保留快速发布，请删除这行代码
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']);
    // 以下这一行代码将删除 "引入链接" 面板
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
    // 以下这一行代码将删除 "插件" 面板
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
    // 以下这一行代码将删除 "近期评论" 面板
    //unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
    // 以下这一行代码将删除 "近期草稿" 面板
    //unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_recent_drafts']);
    // 以下这一行代码将删除 "WordPress 开发日志" 面板
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
    // 以下这一行代码将删除 "其它 WordPress 新闻" 面板
    unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);
    // 以下这一行代码将删除 "概况" 面板
    unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']);
// 添加面板
    wp_add_dashboard_widget('custom_help_widget', '帮助', 'custom_dashboard_help');
}
function custom_dashboard_help() {
    echo "可以在这里获得帮助：<a href='http://blog.king51.com'>http://blog.king51.com</a>";     
}
add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' );
/* Add post formats */
//add_theme_support('post-formats', array( 'aside', 'gallery','chat','link','image','quote','status','video') );
/*-----thumbnails suport-----*/
add_theme_support( 'post-thumbnails' );
/* Side bar */
if ( function_exists('register_sidebar') )
     register_sidebar(array(
		'name'			=> 'Main Sidebar',
		'before_widget' => '<div class="shadowblock_out">',
		'after_widget' => '</div></div>',
		'before_title' => '<div class="shadowblock"><h2 class="dotted">',
		'after_title' => '</h2>'
    ));
/* 自定义文章类型 */
 add_action( 'init', 'create_websites');
  function create_websites() {  
   $labels = array(    
	    'name' => _x('网站', 'post type general name'),
	    'singular_name' => _x('websites', 'post type singular name'),
	    'add_new' => _x('添加新网站', '网站'),
	    'add_new_item' => __('添加网站页面'), 
	    'edit_item' => __('编辑网站'),     
	    'new_item' => __('New 网站'),    
	    'view_item' => __('View 网站'),     
	    'search_items' => __('搜索 网站'),    
	    'not_found' =>  __('没有网站'),    
	    'not_found_in_trash' => __('No website found in Trash'),    
	    'parent_item_colon' => '' ,
     	'menu_name' => '网站' 
   );    
	$args = array(
	        'labels' => $labels,
	        'public' => true,
	        'publicly_queryable' => true,
	        'show_ui' => true,
	        'show_in_menu' => true,
	        'query_var' => true,
	        'rewrite' => true,
	        'capability_type' => 'post',
	        'has_archive' => true,
	        'hierarchical' => false,
	        'menu_position' => null,
	        'supports' => array('title','editor','revisions'),
	        'taxonomies' => array('post_tag','category')
	    );
	    register_post_type('k_website',$args);
}
/*-----------*/
 add_action( 'init', 'create_apps_init' );
  function create_apps_init() {  
   $labels = array(    
	    'name' => _x('软件', 'post type general name'),
	    'singular_name' => _x('apps', 'post type singular name'),
	    'add_new' => _x('添加新软件', '程'),
	    'add_new_item' => __('添加新软件页面'), 
	    'edit_item' => __('编辑软件'),     
	    'new_item' => __('添加新软件'),    
	    'view_item' => __('所有软件'),     
	    'search_items' => __('搜索软件'),    
	    'not_found' =>  __('没有内容'),    
	    'not_found_in_trash' => __('No APPS found in Trash'),    
	    'parent_item_colon' => '',
     	'menu_name' => '软件' 
   );    
	$args = array(
	        'labels' => $labels,
	        'public' => true,
	        'publicly_queryable' => true,
	        'show_ui' => true,
	        'show_in_menu' => true,
	        'query_var' => true,
	        'rewrite' => true,
	        'capability_type' => 'post',
	        'has_archive' => true,
	        'hierarchical' => false,
	        'menu_position' => null,
	        'supports' => array('title','editor','revisions'),
	        'taxonomies' => array('post_tag','category')
	    );
	    register_post_type('k_app',$args);
}
/* 自定义分类，暂时用不到  
-------------------
add_action( 'init', 'create_k_system' );
function create_k_system() {
 $labels = array(
    'name' => _x( '平台分类', 'taxonomy general name' ),
    'singular_name' => _x( 'k_system', 'taxonomy singular name' ),
    'search_items' =>  __( '搜索平台' ),
    'all_items' => __( 'All 平台' ),
    'parent_item' => __( 'Parent 平台' ),
    'parent_item_colon' => __( 'Parent 平台:' ),
    'edit_item' => __( '编辑平台类别' ),
    'update_item' => __( '更新平台类别' ),
    'add_new_item' => __( '添加新平台' ),
    'new_item_name' => __( '新平台名称' ),
  ); 	
  register_taxonomy('k_system',array('post','k_app','k_website'),array(
    'hierarchical' => true,
    'labels' => $labels
  ));
}
----------------------
*/
/* 添加自定义字段面板 */
//创建字段信息
$new_meta_boxes = array(
    "myurls" => array(
        "name" => "myurls",
        "std" => "http://",
        "title" => "关键字:"));
//创建自定义字段输入框
function new_meta_boxes() {
    global $post, $new_meta_boxes;
    foreach($new_meta_boxes as $meta_box) {
        $meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);
        if($meta_box_value == "")
            $meta_box_value = $meta_box['std'];
        echo'<input type="hidden" name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';
        // 自定义字段标题
        // echo'<h4>'.$meta_box['title'].'</h4>';
        // 自定义字段输入框
        echo '<input type="text" size=60 name="'.$meta_box['name'].'_value" value='.$meta_box_value.' /><br />';
    }}
//创建自定义字段模块
function create_meta_box() {
    global $theme_name;
    if ( function_exists('add_meta_box') ) {
        add_meta_box( 'new-meta-boxes', '添加地址', 'new_meta_boxes', 'app', 'normal', 'high' );
        add_meta_box( 'new-meta-boxes', '添加地址', 'new_meta_boxes', 'website', 'normal', 'high' );
    }}
//保存文章数据
function save_postdata( $post_id ) {
    global $post, $new_meta_boxes;
    foreach($new_meta_boxes as $meta_box) {
        if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) ))  {
            return $post_id;
        }
        if ( 'page' == $_POST['post_type'] ) {
            if ( !current_user_can( 'edit_page', $post_id ))
                return $post_id;
        } 
        else {
            if ( !current_user_can( 'edit_post', $post_id ))
                return $post_id;
        }
        $data = $_POST[$meta_box['name'].'_value'];
        if(get_post_meta($post_id, $meta_box['name'].'_value') == "")
            add_post_meta($post_id, $meta_box['name'].'_value', $data, true);
        elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
            update_post_meta($post_id, $meta_box['name'].'_value', $data);
        elseif($data == "")
            delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
    }}
//将函数连接到指定action（动作）
add_action('admin_menu', 'create_meta_box');
add_action('save_post', 'save_postdata');
/*--------end-----*/
/** 名称：文章目录插件 博客：http://www.ludou.org/ ****/
function article_index($content) {
    $matches = array();
    $ul_li = '';
    $r = "/<h3>([^<]+)<\/h3>/im";
    if(preg_match_all($r, $content, $matches)) {
        foreach($matches[1] as $num => $title) {
            $content = str_replace($matches[0][$num], '<h4 id="title-'.$num.'">'.$title.'</h4>', $content);
            $ul_li .= '<li><a href="#title-'.$num.'" title="'.$title.'">'.$title."</a></li>\n";
        }
        $content = "\n<div id=\"article-index\">
                <strong>文章目录</strong>
                <ul id=\"index-ul\">\n" . $ul_li . "</ul>
            </div>\n" . $content;
    }
    return $content;
}
add_filter( "the_content", "article_index" );
/* HTTP Gzip */
function wp_gzip() {
  // Dont use on Admin HTML editor
  if ( strstr($_SERVER['REQUEST_URI'], '/js/tinymce') )
    return false;
  // Can't use zlib.output_compression and ob_gzhandler at the same time
  if ( ( ini_get('zlib.output_compression') == 'On' || ini_get('zlib.output_compression_level') > 0 ) || ini_get('output_handler') == 'ob_gzhandler' )
    return false;
  // Load HTTP Compression if correct extension is loaded
  if (extension_loaded('zlib') && !ob_start('ob_gzhandler'))
    ob_start();
}
add_action('init', 'wp_gzip');
/* UTF-8 substr() for none mb_substr() */
if ( !function_exists('mb_substr') ) {
  function mb_substr( $str, $start, $length, $encoding ) {
    return preg_replace( '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $start . '}'.
    '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,' . $length . '}).*#s', '$1', $str);
  }
}
function king51_nav( $p = 2 ) {  // 取当前页前後各 2 页
  if ( is_singular() ) return; // 文章与插页不用
  global $wp_query, $paged;
  $max_page = $wp_query->max_num_pages;
  if ( $max_page == 1 ) return; // 只有一页不用
  if ( empty( $paged ) ) $paged = 1;
  // echo '<span class="pages">Page: ' . $paged . ' of ' . $max_page . ' </span> '; // 页数
  if ( $paged > $p + 1 ) p_link( 1, '最前页' );
  if ( $paged > $p + 2 ) echo "<span class='dots'> ... </span>";
  for( $i = $paged - $p; $i <= $paged + $p; $i++ ) { // 中间页
    if ( $i > 0 && $i <= $max_page ) $i == $paged ? print "<span class='page-numbers current'>{$i}</span> " : p_link( $i );
  }
  if ( $paged < $max_page - $p - 1 ) echo "<span class='dots'> ... </span>";
  if ( $paged < $max_page - $p ) p_link( $max_page, '最后页' );
}
function p_link( $i, $title = '' ) {
  if ( $title == '' ) $title = "第 {$i} 页";
  echo "<a class='page-numbers' href='", esc_html( get_pagenum_link( $i ) ), "' title='{$title}'>{$i}</a> ";
}
// -- END ----------------------------------------
/* <<小墙>> Anti-Spam v1.82 by Willin Kan. 2010/12/16 最新修改 */
//建立
class anti_spam {
  function anti_spam() {
    if ( !current_user_can('level_0') ) {
      add_action('template_redirect', array($this, 'w_tb'), 1);
      add_action('init', array($this, 'gate'), 1);
      add_action('preprocess_comment', array($this, 'sink'), 1);
    }
  }
  //设栏位
  function w_tb() {
    if ( is_singular() ) {
      ob_start(create_function('$input','return preg_replace("#textarea(.*?)name=([\"\'])comment([\"\'])(.+)/textarea>#",
      "textarea$1name=$2w$3$4/textarea><textarea name=\"comment\" cols=\"100%\" rows=\"4\" style=\"display:none\"></textarea>",$input);') );
    }}
  //检查
  function gate() {
    if ( !empty($_POST['w']) && empty($_POST['comment']) ) {
      $_POST['comment'] = $_POST['w'];
    } else {
      $request = $_SERVER['REQUEST_URI'];
      $referer = isset($_SERVER['HTTP_REFERER'])         ? $_SERVER['HTTP_REFERER']         : '隐瞒';
      $IP      = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] . ' (透过代理)' : $_SERVER["REMOTE_ADDR"];
      $way     = isset($_POST['w'])                      ? '手动操作'                       : '未经评论表格';
      $spamcom = isset($_POST['comment'])                ? $_POST['comment']                : null;
      $_POST['spam_confirmed'] = "请求: ". $request. "\n来路: ". $referer. "\nIP: ". $IP. "\n方式: ". $way. "\n内容: ". $spamcom. "\n -- 记录成功 --";
    }}
  //处理
  function sink( $comment ) {
    if ( !empty($_POST['spam_confirmed']) ) {
      if ( in_array( $comment['comment_type'], array('pingback', 'trackback') ) ) return $comment; //不管 Trackbacks/Pingbacks
      //方法一: 直接挡掉, 将 die(); 前面两斜线删除即可.
      die();
      //方法二: 标记为 spam, 留在资料库检查是否误判.
      //add_filter('pre_comment_approved', create_function('', 'return "spam";'));
     // $comment['comment_content'] = "[ 小墙判断这是Spam! ]\n". $_POST['spam_confirmed'];
    }
    return $comment;
  }}
$anti_spam = new anti_spam();
// -- END ----------------------------------------
/* Auto-description v1.3 by Willin Kan. */
function head_meta_desc() {
  global $s, $post;
  $description = '';
  $blog_name = get_bloginfo('name');
  if ( is_singular() ) {
    if( !empty( $post->post_excerpt ) ) {
      $text = $post->post_excerpt;
    } else {
      $text = $post->post_content;
    }
    $description = trim( str_replace( array( "\r\n", "\r", "\n", "　", " "), " ", str_replace( "\"", "'", strip_tags( $text ) ) ) );
    if ( !( $description ) ) $description = $blog_name . " - " . trim( wp_title('', false) );
  } elseif ( is_home () )    { $description = $blog_name . " - " . get_bloginfo('description') . " 一个程序员出身的IT Manager，主要记录技术和生活，涉及企业管理，财务管理，hr等。"; // 首页要自己加
  } elseif ( is_tag() )      { $description = $blog_name . "有关 '" . single_tag_title('', false) . "' 的文章";
  } elseif ( is_category() ) { $description = $blog_name . "有关 '" . single_cat_title('', false) . "' 的文章";
  } elseif ( is_archive() )  { $description = $blog_name . "在: '" . trim( wp_title('', false) ) . "' 的文章";
  } elseif ( is_search() )   { $description = $blog_name . ": '" . esc_html( $s, 1 ) . "' 的搜索結果";
  } else { $description = $blog_name . "有关 '" . trim( wp_title('', false) ) . "' 的文章";
  }
  $description = mb_substr( $description, 0, 97, 'utf-8' ) . '..';
  echo "<meta name=\"description\" content=\"$description\" />\n";
}
add_action('wp_head', 'head_meta_desc');
/* Auto-keywords v1.6 by Willin Kan. */
function tags_category_to_keywords() {
  global $s, $post;
  $keywords = '';
  if ( is_single() ) {
    if ( get_the_tags( $post->ID ) ) {
      foreach ( get_the_tags( $post->ID ) as $tag ) $keywords .= $tag->name . ', ';
    }
    foreach ( get_the_category( $post->ID ) as $category ) $keywords .= $category->cat_name . ', ';
    $keywords = substr_replace( $keywords, "" , -2 );
  } elseif ( is_home () )    { $keywords = "king,月亮上的妖精,king51,IT技术,wp技巧,追求理想"; // 首页要自己加
  } elseif ( is_tag() )      { $keywords = single_tag_title('', false);
  } elseif ( is_category() ) { $keywords = single_cat_title('', false);
  } elseif ( is_search() )   { $keywords = esc_html( $s, 1 );
  } else { $keywords = trim( wp_title('', false) );
  }
  if ( $keywords ) {
    echo "<meta name=\"keywords\" content=\"$keywords\" />\n";
  }
}
add_action('wp_head', 'tags_category_to_keywords');
/*----------嵌套评论开始---------------*/
if ( ! function_exists( 'king51_comment' ) ) :
/**
 * 嵌套评论代码.
 */
function king51_comment( $comment, $args, $depth ) {
	$GLOBALS['comment'] = $comment;
	switch ( $comment->comment_type ) :
		case '' :
	?>
	<li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
		<div id="comment-<?php comment_ID(); ?>">
		<div class="comment-author vcard">
			<?php echo get_avatar( $comment, 50 ); ?>
			<dt><?php echo get_comment_author_link(); ?></dt>
		</div><!-- .comment-author .vcard -->
		<time datetime="<?php echo get_comment_date() . '' . get_comment_time(); ?>"><a href="<?php echo esc_url( get_comment_link( $comment->comment_ID ) ); ?>">
			<?php echo get_comment_date() .' '. get_comment_time(); ?></a>
		</time><?php edit_comment_link(  '(Edit)', ' ' );?><!-- .comment-meta .commentmetadata -->
		<dd class="comment-body">
			<?php if ( $comment->comment_approved == '0' ) : ?>
			<em> 您的评论等待审核。</em>
			<?php endif; ?>
			<?php comment_text(); ?>
		</dd>
		<div class="reply">
			<?php comment_reply_link( array_merge( $args, array( 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
		</div><!-- .reply -->
	</div><!-- #comment-##  -->
	<?php
			break;
		case 'pingback'  :
		case 'trackback' :
	?>
	<li class="post pingback">
		<p>Pingback <?php comment_author_link(); ?><?php edit_comment_link( '(Edit)', ' ' ); ?></p>
	<?php
			break;
	endswitch;
}
endif;
/* 面包屑导航 */
function dimox_breadcrumbs() {
  $delimiter = '&raquo;';
  $name = '首页'; //text for the 'Home' link
  $currentBefore = '<span>';
  $currentAfter = '</span>';
  if ( !is_home() && !is_front_page() || is_paged() ) {
    echo '<h5>您当前位于: ';
    global $post;
    $home = get_bloginfo('url');
    echo '<a href="' . $home . '">' . $name . '</a> ' . $delimiter . ' ';
    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      echo $currentBefore . 'Archive by category &#39;';
      single_cat_title();
      echo '&#39;' . $currentAfter;
    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('d') . $currentAfter;
    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('F') . $currentAfter;
    } elseif ( is_year() ) {
      echo $currentBefore . get_the_time('Y') . $currentAfter;
    } elseif ( is_single() ) {
      $cat = get_the_category(); $cat = $cat[0];
    //  echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_page() && !$post->post_parent ) {
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;
    } elseif ( is_search() ) {
      echo $currentBefore . 'Search results for &#39;' . get_search_query() . '&#39;' . $currentAfter;
    } elseif ( is_tag() ) {
      echo $currentBefore . 'Posts tagged &#39;';
      single_tag_title();
      echo '&#39;' . $currentAfter;
    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $currentBefore . 'Articles posted by ' . $userdata->display_name . $currentAfter;
    } elseif ( is_404() ) {
      echo $currentBefore . 'Error 404' . $currentAfter;
    }
    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('Page') . ' ' . get_query_var('paged');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }
    echo '</h5>';
  }
}
// 自定义菜单
register_nav_menus( array( 'header-menu' =>'头部导航' , 'footer-menu' =>'页脚导航'));
//-------------------------------------------------------------
function cp_login_head() {
    if (is_user_logged_in()) :
        global $current_user;
        get_currentuserinfo();
        ?>
        <?php _e('Welcome,','cp'); ?> <strong><?php echo $current_user->user_login; ?></strong> [ <a href="<?php echo CP_DASHBOARD_URL ?>"><?php _e('My Dashboard','cp'); ?></a> | <a href="<?php echo wp_logout_url(); ?>"><?php _e('Log out','cp'); ?></a> ]&nbsp;
    <?php else : ?>
        <?php _e('Welcome,','cp'); ?> <strong><?php _e('visitor!','cp'); ?></strong> [ <a href="<?php echo get_option('home'); ?>/wp-login.php?action=register"><?php _e('Register','cp'); ?></a> | <a href="<?php echo get_option('home'); ?>/wp-login.php"><?php _e('Login','cp'); ?></a> ]&nbsp;
    <?php endif;
}
?>
